import 'package:flutter/material.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import '../base/base_state.dart';
import '../base/list_state.dart';
import '../base/refresh_state.dart';

/// 状态构建器组件
class StateBuilder<T> extends StatelessWidget {
  final BaseState<T> state;
  final Widget Function(BuildContext context, T data) onSuccess;
  final Widget Function(BuildContext context)? onLoading;
  final Widget Function(BuildContext context)? onEmpty;
  final Widget Function(BuildContext context, String error)? onError;
  final VoidCallback? onRetry;

  const StateBuilder({
    super.key,
    required this.state,
    required this.onSuccess,
    this.onLoading,
    this.onEmpty,
    this.onError,
    this.onRetry,
  });

  @override
  Widget build(BuildContext context) {
    switch (state.status) {
      case PageStatus.loading:
        return onLoading?.call(context) ?? const DefaultLoadingWidget();
      case PageStatus.empty:
        return onEmpty?.call(context) ?? DefaultEmptyWidget(onRetry: onRetry);
      case PageStatus.error:
        return onError?.call(context, state.errorMessage ?? '未知错误') ??
            DefaultErrorWidget(
              message: state.errorMessage ?? '未知错误',
              onRetry: onRetry,
            );
      case PageStatus.success:
        if (state.hasData) {
          return onSuccess(context, state.data!);
        } else {
          return onEmpty?.call(context) ?? DefaultEmptyWidget(onRetry: onRetry);
        }
      case PageStatus.idle:
        return onLoading?.call(context) ?? const DefaultLoadingWidget();
    }
  }
}

/// 异步状态构建器组件
class AsyncStateBuilder<T> extends ConsumerWidget {
  final AsyncValue<T> asyncValue;
  final Widget Function(BuildContext context, T data) onData;
  final Widget Function(BuildContext context)? onLoading;
  final Widget Function(
      BuildContext context, Object error, StackTrace stackTrace)? onError;
  final VoidCallback? onRetry;

  const AsyncStateBuilder({
    super.key,
    required this.asyncValue,
    required this.onData,
    this.onLoading,
    this.onError,
    this.onRetry,
  });

  @override
  Widget build(BuildContext context, WidgetRef ref) {
    return asyncValue.when(
      data: (data) => onData(context, data),
      loading: () => onLoading?.call(context) ?? const DefaultLoadingWidget(),
      error: (error, stackTrace) =>
          onError?.call(context, error, stackTrace) ??
          DefaultErrorWidget(
            message: error.toString(),
            onRetry: onRetry,
          ),
    );
  }
}

/// 列表状态构建器组件
class ListStateBuilder<T> extends StatelessWidget {
  final ListState<T> state;
  final Widget Function(BuildContext context, List<T> items) onSuccess;
  final Widget Function(BuildContext context)? onLoading;
  final Widget Function(BuildContext context)? onEmpty;
  final Widget Function(BuildContext context, String error)? onError;
  final VoidCallback? onRetry;
  final VoidCallback? onLoadMore;
  final Widget? loadMoreWidget;

  const ListStateBuilder({
    super.key,
    required this.state,
    required this.onSuccess,
    this.onLoading,
    this.onEmpty,
    this.onError,
    this.onRetry,
    this.onLoadMore,
    this.loadMoreWidget,
  });

  @override
  Widget build(BuildContext context) {
    Widget content;

    switch (state.status) {
      case PageStatus.loading:
        content = onLoading?.call(context) ?? const DefaultLoadingWidget();
        break;
      case PageStatus.empty:
        content =
            onEmpty?.call(context) ?? DefaultEmptyWidget(onRetry: onRetry);
        break;
      case PageStatus.error:
        content = onError?.call(context, state.errorMessage ?? '未知错误') ??
            DefaultErrorWidget(
              message: state.errorMessage ?? '未知错误',
              onRetry: onRetry,
            );
        break;
      case PageStatus.success:
        if (state.items.isNotEmpty) {
          content = Column(
            children: [
              Expanded(child: onSuccess(context, state.items)),
              if (state.isLoadingMore)
                loadMoreWidget ?? const DefaultLoadMoreWidget(),
            ],
          );
        } else {
          content =
              onEmpty?.call(context) ?? DefaultEmptyWidget(onRetry: onRetry);
        }
        break;
      case PageStatus.idle:
        content = onLoading?.call(context) ?? const DefaultLoadingWidget();
        break;
    }

    return content;
  }
}

/// 刷新列表状态构建器组件
class RefreshListBuilder<T> extends StatelessWidget {
  final RefreshState<T> state;
  final Widget Function(BuildContext context, List<T> items) onSuccess;
  final Widget Function(BuildContext context)? onLoading;
  final Widget Function(BuildContext context)? onEmpty;
  final Widget Function(BuildContext context, String error)? onError;
  final VoidCallback? onRetry;
  final VoidCallback? onRefresh;
  final VoidCallback? onLoadMore;
  final Widget? loadMoreWidget;
  final ScrollController? scrollController;

  const RefreshListBuilder({
    super.key,
    required this.state,
    required this.onSuccess,
    this.onLoading,
    this.onEmpty,
    this.onError,
    this.onRetry,
    this.onRefresh,
    this.onLoadMore,
    this.loadMoreWidget,
    this.scrollController,
  });

  @override
  Widget build(BuildContext context) {
    Widget content;

    switch (state.status) {
      case PageStatus.loading:
        content = onLoading?.call(context) ?? const DefaultLoadingWidget();
        break;
      case PageStatus.empty:
        content =
            onEmpty?.call(context) ?? DefaultEmptyWidget(onRetry: onRetry);
        break;
      case PageStatus.error:
        content = onError?.call(context, state.errorMessage ?? '未知错误') ??
            DefaultErrorWidget(
              message: state.errorMessage ?? '未知错误',
              onRetry: onRetry,
            );
        break;
      case PageStatus.success:
        if (state.items.isNotEmpty) {
          content = Column(
            children: [
              Expanded(child: onSuccess(context, state.items)),
              if (state.isLoadingMore)
                loadMoreWidget ?? const DefaultLoadMoreWidget(),
            ],
          );
        } else {
          content =
              onEmpty?.call(context) ?? DefaultEmptyWidget(onRetry: onRetry);
        }
        break;
      case PageStatus.idle:
        content = onLoading?.call(context) ?? const DefaultLoadingWidget();
        break;
    }

    // 包装RefreshIndicator
    if (onRefresh != null && state.status == PageStatus.success) {
      return RefreshIndicator(
        onRefresh: () async {
          onRefresh?.call();
          // 等待刷新完成
          await Future.delayed(const Duration(milliseconds: 100));
        },
        child: content,
      );
    }

    return content;
  }
}

/// 默认加载组件
class DefaultLoadingWidget extends StatelessWidget {
  final String? message;

  const DefaultLoadingWidget({super.key, this.message});

  @override
  Widget build(BuildContext context) {
    return Center(
      child: Column(
        mainAxisAlignment: MainAxisAlignment.center,
        children: [
          const CircularProgressIndicator(),
          if (message != null) ...[
            SizedBox(height: 16),
            Text(
              message!,
              style: TextStyle(
                fontSize: 14,
                color: Colors.black,
              ),
            ),
          ],
        ],
      ),
    );
  }
}

/// 默认空数据组件
class DefaultEmptyWidget extends StatelessWidget {
  final String? message;
  final String? buttonText;
  final VoidCallback? onRetry;
  final Widget? icon;

  const DefaultEmptyWidget({
    super.key,
    this.message,
    this.buttonText,
    this.onRetry,
    this.icon,
  });

  @override
  Widget build(BuildContext context) {
    return Center(
      child: Column(
        mainAxisAlignment: MainAxisAlignment.center,
        children: [
          icon ??
              Icon(
                Icons.inbox_outlined,
                size: 64,
                color: Colors.grey,
              ),
          SizedBox(height: 16),
          Text(
            message ?? '暂无数据',
            style: TextStyle(
              fontSize: 16,
              color: Colors.black,
            ),
          ),
          if (onRetry != null) ...[
            SizedBox(height: 24),
            ElevatedButton(
              onPressed: onRetry,
              style: ElevatedButton.styleFrom(
                backgroundColor: Colors.red,
                foregroundColor: Colors.white,
                shape: RoundedRectangleBorder(
                  borderRadius: BorderRadius.circular(8),
                ),
              ),
              child: Text(buttonText ?? '重试'),
            ),
          ],
        ],
      ),
    );
  }
}

/// 默认错误组件
class DefaultErrorWidget extends StatelessWidget {
  final String message;
  final String? buttonText;
  final VoidCallback? onRetry;
  final Widget? icon;

  const DefaultErrorWidget({
    super.key,
    required this.message,
    this.buttonText,
    this.onRetry,
    this.icon,
  });

  @override
  Widget build(BuildContext context) {
    return Center(
      child: Padding(
        padding: EdgeInsets.all(24),
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: [
            icon ??
                Icon(
                  Icons.error_outline,
                  size: 64,
                  color: Colors.red,
                ),
            SizedBox(height: 16),
            Text(
              message,
              textAlign: TextAlign.center,
              style: TextStyle(
                fontSize: 16,
                color: Colors.black,
              ),
            ),
            if (onRetry != null) ...[
              SizedBox(height: 24),
              ElevatedButton(
                onPressed: onRetry,
                style: ElevatedButton.styleFrom(
                  backgroundColor: Colors.red,
                  foregroundColor: Colors.white,
                  shape: RoundedRectangleBorder(
                    borderRadius: BorderRadius.circular(8),
                  ),
                ),
                child: Text(buttonText ?? '重试'),
              ),
            ],
          ],
        ),
      ),
    );
  }
}

/// 默认加载更多组件
class DefaultLoadMoreWidget extends StatelessWidget {
  final String? message;

  const DefaultLoadMoreWidget({super.key, this.message});

  @override
  Widget build(BuildContext context) {
    return Container(
      padding: EdgeInsets.all(16),
      child: Row(
        mainAxisAlignment: MainAxisAlignment.center,
        children: [
          SizedBox(
            width: 16,
            height: 16,
            child: const CircularProgressIndicator(strokeWidth: 2),
          ),
          SizedBox(width: 8),
          Text(
            message ?? '加载中...',
            style: TextStyle(
              fontSize: 14,
              color: Colors.black,
            ),
          ),
        ],
      ),
    );
  }
}
